// express   项目的核心文件

var createError = require('http-errors');    //http   异常监听
var express = require('express');    //   express  插件
var path = require('path');   //    Node   自带的模块
var cookieParser = require('cookie-parser');    //   编译cookies
var logger = require('morgan');    //   记录日志
var session = require('express-session')

//引入数据库    链接数据库
require("./db/connect")

var cors = require('cors')
//解决跨越的问题

//路由模块
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var apiRouter = require('./routes/api');
var partyRouter = require("./routes/party")
var adviseRouter = require("./routes/advise")
var organizeRouter = require("./routes/organize")


//   app 包含了   express所有的语法
var app = express();

app.use(cors()); // cors 配置管理  

// view engine setup
app.set('views', path.join(__dirname, 'views'));    //  views这个重置路径  根路径
app.set('view engine', 'ejs');   //   模板引擎    ejs

app.use(logger('dev'));    //  dev   开发环境的日志
app.use(express.json());    //   post   提交的数据   axios.post
app.use(express.urlencoded({ extended: false }));    //post 提交的form表单
app.use(cookieParser());    //设置使用   cookies  插件
app.use(express.static(path.join(__dirname, 'public')));    //static  静态  express静态目录  （直接读取）   public  重置



// 3. 设置session 中间件 
app.use(session({
  secret: 'wh2114-daydayup',
  name: 'MyTest',
  cookie: {maxAge: 60 * 1000  * 60 * 2 },    // 有效时间长 2h
  resave: false, 
  saveUninitialized: true
}));


//使用路由模块
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/api', apiRouter);
app.use('/party',partyRouter)
app.use('/advise',adviseRouter)
app.use('/organize',organizeRouter)

// app.use(中间件)
app.use(function(req,res,next){
  console.log("路由匹配失败 -- 404");
  next()
})

// catch 404 and forward to error handler
app.use(function(req, res, next) {

  //next   进入下一个中间件
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);

  // res.render(模板)
  res.render('error');   //就是views   里面的error.ejs
});

module.exports = app;
